import json
import os
import logging


class ConfigManager:
    def __init__(self, config_file='config.json', logger=None):
        self.config_file = os.path.abspath(config_file)
        self.logger = logger or logging.getLogger(__name__)
        self.config = self.load()

    def load(self):
        # 加载配置文件，如果不存在则创建默认配置
        default_config = {
            'focus_duration': 90,
            'break_duration': 20,
            'min_interval': 10,
            'max_interval': 15,
            'sound_enabled': True,
            'notifications_enabled': True,
            'speed_factor': 1
        }

        if not os.path.exists(self.config_file):
            self._save_config(default_config)
            self.logger.info(f'Created new config file at {self.config_file}')
            return default_config

        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            self.logger.error(f'Error loading config: {str(e)}')
            return default_config

    def _save_config(self, config_data):
        try:
            # 确保配置文件路径有效
            if not self.config_file:
                self.config_file = os.path.join(os.getcwd(), 'config.json')
            # 创建目录（如果不存在）
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            self.logger.error(f'Failed to save config: {str(e)}')
            return False

    def save(self):
        return self._save_config(self.config)

    def get(self, key, default=None):
        return self.config.get(key, default)

    def set(self, key, value):
        self.config[key] = value
        self._save_config(self.config)

    def update(self, config_dict):
        self.config.update(config_dict)
        self._save_config(self.config)

    def reset_defaults(self):
        default_config = {
            'focus_duration': 90,
            'break_duration': 20,
            'min_interval': 10,
            'max_interval': 15,
            'sound_enabled': True,
            'notifications_enabled': True,
            'speed_factor': 1
        }
        self.config = default_config
        self._save_config(default_config)
        self.logger.info('Configuration reset to default values')

    def get_all(self):
        return self.config.copy()

    def __getitem__(self, key):
        return self.config.get(key)

    def __setitem__(self, key, value):
        self.config[key] = value
        self._save_config(self.config)

    def __contains__(self, key):
        return key in self.config
